package com.sql.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Database {
	private IConnectionFactory connectionFactory = null;

	public Database(IConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List ExecuteQuery(String sqlStatement, IRowMapper rowMapper)
			throws Exception {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		List result = new ArrayList();

		try {
			connection = connectionFactory.createConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sqlStatement);
			while (resultSet.next()) {
				result.add(rowMapper.mapRow(resultSet));
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (resultSet != null)
				resultSet.close();
			if (statement != null)
				statement.close();
			if (connection != null)
				connection.close();
		}
		return result;
	}

	public int ExecuteNonQuery(String sqlStatement) throws Exception {
		Connection connection = null;
		Statement statement = null;
		int numberOfRows = 0;

		try {
			connection = connectionFactory.createConnection();
			statement = connection.createStatement();
			numberOfRows = statement.executeUpdate(sqlStatement);
		} catch (Exception e) {
			throw e;
		} finally {
			if (statement != null)
				statement.close();
			if (connection != null)
				connection.close();
		}
		return numberOfRows;
	}

	public int[] ExecuteNonQuery(List<String> sqlStatements) throws Exception {
		Connection connection = null;
		Statement statement = null;
		int[] numberOfRows;

		try {
			connection = connectionFactory.createConnection();
			statement = connection.createStatement();
			for (String sqlStatement : sqlStatements) {
				statement.addBatch(sqlStatement);
			}
			numberOfRows = statement.executeBatch();
		} catch (Exception e) {
			throw e;
		} finally {
			if (statement != null)
				statement.close();
			if (connection != null)
				connection.close();
		}
		return numberOfRows;
	}

}
